import React,{Component} from 'react'
import PropTypes from 'prop-types'
import { Upload, Modal,message } from 'antd';
import { PlusOutlined } from '@ant-design/icons';

import {reqDeleteImg} from "../../api";
import {BASE_IMG_URL} from "../../utils/constants";

export default class PicturesWall extends Component {

    static propsTypes = {
        imgs: PropTypes.array
    }

    state = {
        previewVisible: false, //标识是否显示大图预览Modal
        previewImage: '', //大图的url
        previewTitle: '',
        fileList: [
            /*{
                uid: '-1', //每一个file都有自己唯一的id
                name: 'image.png',// 图片文件名
                status: 'done',// 图片状态： done(已上传),uploading(正在上传中),removed(已删除)
                url: 'https://zos.alipayobjects.com/rmsportal/jkjgkEfvpUPVyRjUImniVslZfWPnJuuZ.png', //图片地址
            }*/
        ],
    };

    constructor(props) {
        super(props);

        let fileList = [] //初始化图片存放数组

        // 如果传入了imgs属性
        const {imgs} = this.props
        if(imgs && imgs.length>0){
            fileList = imgs.map((img,index) => ({
                uid:-index, //每个file都有自己唯一的id
                name: img, //图片文件名
                status:'done', //图片状态
                url:BASE_IMG_URL+img
            }))
        }

        // 初始化状态
        this.state = {
            previewVisible: false, //标识是否显示大图预览Modal
            previewImage: '', //大图的url
            fileList //所有已上传图片的数组
        }
    }

    /*
    * 隐藏Modal
    * */
    handleCancel = () => this.setState({ previewVisible: false });

    onPreview = async file => {
        /*
        if (!file.url && !file.preview) {
            file.preview = await getBase64(file.originFileObj);
        }

        //显示指定file对应的大图
        this.setState({
            previewImage: file.url || file.preview,
            previewVisible: true,
            previewTitle: file.name || file.url.substring(file.url.lastIndexOf('/') + 1),
        });
        */

        let src = file.url
        if(!src){
            src = await new Promise(resolve => {
                const reader = new FileReader()
                reader.readAsDataURL(file.originFileObj)
                reader.onload = () => resolve(reader.result)
            })
        }
        const image = new Image()
        image.src = src
        const imgWindow = window.open(src)
        imgWindow.document.write(image.outerHTML)
    };

    //获取所有已经上传图片文件名的数组
    getImgs = () => {
        const {fileList} = this.state
        return fileList.map(file => {
            return file.name
        })
    }

    /*
    * file: 当前操作的图片文件（上传/删除）
    * fileList：所有已上传图片文件的数组
    * */
    handleChange =async ({ file,fileList }) => {
        //file != fileList[fileList.length-1]

        //一旦上传成功，将当前上传的file的信息修正（name,url）
        if(file.status === 'done'){
            const result = file.response // {status: 0,data: {name: 'xxx.jpg',url: '图片地址'}}
            if(result.status === 0){
                message.success("上传图片成功")
                const {name,url} = result.data
                file = fileList[fileList.length-1]
                file.name = name
                file.url = url
            }else{
                message.error("上传图片失败")
            }
        }else if(file.status === 'removed'){ //删除图片
            const result = await reqDeleteImg(file.name)
            if(result.status === 0){
                message.success('删除图片成功')
            }else{
                message.error('删除图片失败')
            }
        }

        //在操作（上传/删除）过程中更新fileList状态
        this.setState({ fileList })
    }


    render() {
        const { previewVisible, previewImage, fileList, previewTitle } = this.state;
        const uploadButton = (
            <div>
                <PlusOutlined />
                <div style={{ marginTop: 8 }}>Upload</div>
            </div>
        );
        return (
            <>
                <Upload
                    action="http://39.100.225.255:5000/manage/img/upload" //上传图片的接口地址
                    accept='image/*' //只接收图片格式
                    name='image' //请求参数名
                    listType="picture-card" //设置上传图片的样式 卡片样式
                    fileList={fileList} //所有已上传图片文件对象的数组
                    onPreview={this.onPreview}
                    onChange={this.handleChange}
                >
                    {fileList.length >= 8 ? null : uploadButton}
                </Upload>
                <Modal
                    visible={previewVisible}
                    title={previewTitle}
                    footer={null}
                    onCancel={this.handleCancel}
                >
                    <img alt="example" style={{ width: '100%' }} src={previewImage} />
                </Modal>
            </>
        );
    }
}
